<?php namespace Phpcmf\Controllers\Admin;

class Template extends \Phpcmf\Table
{

    public function __construct()
    {
        parent::__construct();
        // 表单显示名称
        $this->name = dr_lang('模板消息');
        // 模板前缀(避免混淆)
        $this->tpl_prefix = 'template_';
        // 用于表储存的字段，后台可修改的表字段
        $field = array(
            'title' => array(
                'name' => dr_lang('主题'),
                'fieldname' => 'title', // 这是字段名称必须和主键相同
            ),
            'template' => array(
                'name' => dr_lang('模板ID'),
                'fieldname' => 'template', // 这是字段名称必须和主键相同
            ),
            'url' => array(
                'name' => dr_lang('消息URL'),
                'fieldname' => 'url', // 这是字段名称必须和主键相同
            ),
        );
        // 初始化数据表
        $this->_init([
            'table' => weixin_wxtable('template'),
            'field' => $field, // 可查询的字段
            'order_by' => 'inputtime desc', // 列表排序
            'date_field' => 'inputtime', // 按时间段搜索字段
        ]);

        // 把公共变量传入模板
        \Phpcmf\Service::V()->assign([
            // 搜索字段
            'field' => $field,
            // 后台的菜单
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu(
                [
                    $this->name => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index', 'fa fa-edit'],
                    '创建' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/add', 'fa fa-plus'],
                    '修改' => ['hide:'.APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/edit', 'fa fa-edit'],
                ]),
            'group' => \Phpcmf\Service::M('User', APP_DIR)->get_group_data(),
            'ucount' => \Phpcmf\Service::M()->table(weixin_wxtable('user'))->counts(),
        ]);
    }

    // 来自cms的群发
    public function show_add() {

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $mid = dr_safe_filename(\Phpcmf\Service::L('Input')->get('mid'));
        if (!$id || !$mid) {
            $this->_json(0, '参数不能为空');
        }

        $data = \Phpcmf\Service::M()->table_site($mid)->get($id);
        if (!$data) {
            $this->_json(0, '内容不存在');
        }

        $cache = \Phpcmf\Service::M()->table(weixin_wxtable('user'))->getAll();
        if (!$cache) {
            $this->_json(0, dr_lang('没有可用粉丝'));
        }

        $tpl = [];


        // 生成模板
        $template = [];
        foreach ($tpl['content'] as $t) {
            if ($t['name']) {
                $template[$t['name']] = [
                    'value' => $t['value'],
                    'color' => $t['color'],
                ];
            }
        }
        if (!$template) {
            $this->_json(0, dr_lang('模板内容解析后不存在'));
        }

        // 存储文件
        \Phpcmf\Service::L('cache')->set_data('app-weixin-template-send', [
            'data' => $data,
            'template' => $template,
            'users' => dr_save_bfb_data($cache)
        ], 3600);


        $this->_json(1, 'ok', ['url' => dr_url('weixin/template/show_index', ['counts'=> count($cache)])]);
    }

    // 查看列表
    public function index() {
        list($tpl) = $this->_List();
        \Phpcmf\Service::V()->display($tpl);
    }

    // 添加内容
    public function add() {
        list($tpl) =$this->_Post(0);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 修改内容
    public function edit() {

        $id = intval(\Phpcmf\Service::L('Input')->get('id'));
        list($tpl) = $this->_Post($id);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 删除内容
    public function del() {
        $this->_Del(
            \Phpcmf\Service::L('Input')->get_post_ids(),
            null,
            null,
            \Phpcmf\Service::M()->dbprefix($this->init['table'])
        );
    }

    // 内容处理
    public function todo_add() {

        $id = \Phpcmf\Service::L('input')->get('id');
        $data = \Phpcmf\Service::M()->table($this->init['table'])->get($id);
        if (!$data) {
            $this->_json(0, dr_lang('模板内容不存在'));
        } elseif (!$data['content']) {
            $this->_json(0, dr_lang('内容参数不存在'));
        } elseif (!$data['template']) {
            $this->_json(0, dr_lang('模板ID不存在'));
        }

        $data['content'] = dr_string2array($data['content']);
        if ($data['groupid'] < 0) {
            $gid = abs($data['groupid']);
            $where = 'uid in (select uid from '.\Phpcmf\Service::M()->dbprefix('member_group_index').' where gid='.$gid.')';
            $cache = \Phpcmf\Service::M()->table(weixin_wxtable('user'))->where($where)->getAll();
        } elseif ($data['groupid'] > 0) {
            $cache = \Phpcmf\Service::M()->table(weixin_wxtable('user'))->where('groupids LIKE "%\"'.\Phpcmf\Service::M()->db->escapeString($data['groupid'], true).'\"%"')->getAll();
        } else {
            $cache = \Phpcmf\Service::M()->table(weixin_wxtable('user'))->getAll();
        }
        if (!$cache) {
            $this->_json(0, dr_lang('没有可用粉丝'));
        }

        // 生成模板
        $template = [];
        foreach ($data['content'] as $t) {
            if ($t['name']) {
                $template[$t['name']] = [
                    'value' => $t['value'],
                    'color' => $t['color'],
                ];
            }
        }
        if (!$template) {
            $this->_json(0, dr_lang('模板内容解析后不存在'));
        }

        // 存储文件
        \Phpcmf\Service::L('cache')->set_auth_data('app-weixin-template-send', [
            'data' => $data,
            'template' => $template,
            'users' => dr_save_bfb_data($cache)
        ]);

        $this->_json(1, 'ok', ['url' => dr_url('weixin/template/show_index', ['counts'=> count($cache)])]);
    }


    // 内容处理
    public function show_index() {
        \Phpcmf\Service::V()->assign([
            'menu' => '',
            'hidebtn' => 1,
            'todo_url' =>  dr_url('weixin/template/send_add'),
            'count_url' =>  dr_url('weixin/template/show_count_index'),
        ]);
        \Phpcmf\Service::V()->display('bfb.html');exit;
    }

    // 内容数量统计
    public function show_count_index() {

        $data = \Phpcmf\Service::L('cache')->get_auth_data('app-weixin-template-send');
        !dr_count($data) && $this->_json(0, dr_lang('无可用数据'));

        $this->_json(count($data['users']), 'ok');
    }

    public function send_add() {

        $page = max(1, intval($_GET['pp']));
        $cache = \Phpcmf\Service::L('cache')->get_auth_data('app-weixin-template-send');
        !$cache && $this->_json(0, dr_lang('缓存不存在'));

        $data = $cache['users'][$page];
        if ($data) {
            $html = '';
            foreach ($data as $user) {
                $rt = $this->_send_template($user['openid'], $cache['data']['template'], $cache['template'], $cache['data']['url'],  $cache['data']['color']);
                if (!$rt['code']) {
                    $ok = "<span class='error'>".$rt['msg']."</span>";
                    $class = ' p_error';
                } else {
                    $ok = "<span class='ok'>".dr_lang('发送成功')."</span>";
                    \Phpcmf\Service::M()->db->table($this->init['table'])->where('id', intval($cache['data']['id']))->increment('counts', 1);
                }
                $html.= '<p class="'.$class.'"><label class="rleft">'.dr_html2emoji($user['nickname']).'</label><label class="rright">'.$ok.'</label></p>';

            }
            $this->_json($page + 1, $html);
        }

        // 完成
        \Phpcmf\Service::L('cache')->del_auth_data('app-weixin-template-send');
        $this->_json(100, '');
    }



    /**
     * 获取微信 access token
     */
    public function _weixin_template_access_token() {

        $cache_data = \Phpcmf\Service::L('cache')->init('file')->get('access_token');
        if (isset($cache_data['time']) && $cache_data['access_token']) {
            $access_token = $cache_data['access_token'];
        } else {
            $weixin = \Phpcmf\Service::C()->get_cache('weixin');
            $result = wx_get_https_json_data('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$weixin['account']['appid'].'&secret='.$weixin['account']['appsecret']);
            if (!$result['code']) {
                return dr_return_data(0, 'AccessToken：'.$result['msg']);
            }
            \Phpcmf\Service::L('cache')->init('file')->save('access_token', $result['data'], 3600);
            $access_token = $result['data']['access_token'];
        }

        return dr_return_data(1, 'ok', ['access_token' => $access_token]);
    }

    private function _send_template($oid, $id, $data, $url = '', $color = '') {

        $rt = $this->_weixin_template_access_token();
        if (!$rt['code']) {
            return dr_return_data(0, $rt['msg']);
        }

        $p = [
            'touser' => $oid,
            'template_id' => $id,
            'url' => $url,
            'topcolor' => $color,
            'data' => $data,
        ];
        $rt = wx_post_https_json_data('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$rt['data']['access_token'], $p);

        return $rt;
    }

    // 复制
    public function copy_edit() {

        $id = intval(\Phpcmf\Service::L('input')->get('id'));
        $data = \Phpcmf\Service::M()->db->table(weixin_wxtable('template'))->where('id', $id)->get()->getRowArray();
        if (!$data) {
            $this->_json(0, dr_lang('数据#%s不存在', $id));
        }

        unset($data['id']);
        $data['title'].= '_copy';

        $rt = \Phpcmf\Service::M()->table(weixin_wxtable('template'))->insert($data);
        if (!$rt['code']) {
            $this->_json(0, dr_lang($rt['msg']));
        }

        $this->_json(1, dr_lang('复制成功'));
    }

    /**
     * 获取内容
     * $id      内容id,新增为0
     * */
    protected function _Data($id = 0) {

        $data = parent::_Data($id);
        if (!$data) {
            return [];
        }

        $data['content'] = dr_string2array($data['content']);
        return $data;
    }

    // 格式化保存数据
    protected function _Format_Data($id, $data, $old) {

        $data[1] = \Phpcmf\Service::L('input')->post('data');
        $data[1]['content'] = dr_array2string($data[1]['content']);
        if (!$id) {
            // 当提交新数据时，把当前时间插入进去
            $data[1]['counts'] = 0;
            $data[1]['inputtime'] = SYS_TIME;
        }

        return $data;
    }

}
